/**
 * Created by 77element-01 on 2016/3/23.
 */
var instance,
    connectorPaintStyle,
    connectorHoverStyle,
    endpointHoverStyle,
    endpointOptions,
    hollowCircle,
    sourceEndpoint;
/**
 * 处理新建组件的
 */
function iniPlumb() {
    instance = jsPlumb.getInstance({
        DragOptions       : {cursor: 'pointer', zIndex: 2000},//拖动时鼠标停留在该元素上显示指针，通过css控制
        //ConnectionsDetachable: false,//可拆卸的连接
        //ReattachConnections  : true,//重新连接连接
        PaintStyle        : {strokeStyle: '#ccc'},//元素的默认颜色
        //EndpointHoverStyle: {fillStyle: "orange"},//终点悬停样式,fillStyle填充样式
        //HoverPaintStyle: {strokeStyle: "orange"},//悬停绘图样式，strokeStyle笔触样式
        //EndpointStyle: {width: 20, height: 16, strokeStyle: '#666'},//连接点的默认颜色
        //Endpoint: "Rectangle",//连接点的默认形状
        //Anchors: ["TopCenter", "TopCenter"],//连接点的默认位置
        ConnectionOverlays: [
            ["Arrow", {location: 1, width: 10, length: 13}]
        ],
        Connector         : ["Straight"],//连接线的样式种类有[Bezier],[Flowchart],[StateMachine],[Straight]
        Container         : "canvas" //总编辑容器
    });
    //基本连接线样式
    connectorPaintStyle = {
        //fillStyle  : "transparent",
        strokeStyle: "rgb(74,203,129)",
        radius     : 5,
        //joinstyle  : "round",
        lineWidth  : 2,
        zIndex     : 2,
        dashstyle  : "4 4"
    };
    // 鼠标悬浮在连接线上的样式
    connectorHoverStyle = {
        lineWidth   : 3,
        strokeStyle : "#ccc",
        outlineWidth: 2,
        outlineColor: "white"
    };
    endpointHoverStyle = {
        fillStyle  : "#216477",
        strokeStyle: "#216477"
    };

    // 连接点样式1
    endpointOptions = {
        endpoint           : "Dot",
        paintStyle         : {
            strokeStyle: "#CCC",
            fillStyle  : "transparent",
            radius     : 3,
            lineWidth  : 2
        },
        isSource           : true,
        isTarget           : true,
        maxConnections     : -1,
        connectorStyle     : connectorPaintStyle,
        connectorHoverStyle: connectorHoverStyle,
        dragOptions        : {}
    };


    // 连接点样式2
    hollowCircle = {
        dragOptions        : {cursor: 'default', tolerance: "touch",},
        reattach           : true,
        //dragOptions: {},
        endpoint           : ["Dot", {radius: 5}],
        //endpoint: ["Image", {url: 'images.jpeg'}],
        //终点、端点的形状//(endpoint:"Rectangle"//设置连接点的形状为矩形)
        //Blank空|Dot圆形|Rectangle矩形|Image  ["Image",{url:"xxx.png"}]
        connectorStyle     : {
            //fillStyle  : "transparent",
            strokeStyle: "rgb(74,203,129)",
            radius     : 5,
            //joinstyle  : "round",
            lineWidth  : 3,
            //zIndex     : 2,
            dashstyle  : "2 4"//虚线
        },//连接线的颜色，大小样式
        connectorHoverStyle: connectorHoverStyle,//鼠标经过的样式
        paintStyle         : {
            strokeStyle: "#ccc",//笔触样式
            fillStyle  : "transparent",//填充样式；透明
            radius     : 8,//圆角
            lineWidth  : 2,//粗细
            zIndex     : 3,
        },    //端点的颜色样式
        //hoverClass : "myEndpointHover",
        //anchor: "AutoDefault",
        isSource           : true,  //是否可以拖动（作为连线起点）
        //connector: ["Straight", {stub: [0, 0], gap: 10, cornerRadius: 5, alwaysRespectStubs: true}], //连接线的样式种类有[Bezier],[Flowchart],[StateMachine ],[Straight ]
        isTarget           : true,  //是否可以放置（连线终点）
        maxConnections     : -1,  // 设置连接点最多可以连接几条线 -1无限
        //connectorOverlays: [["Arrow", {width: 10, length: 10, location: 1}]]//连接器覆盖
        //Arrow|Diamond|Label|PlainArrow
        overlays           : [//覆盖
            ["Label", {
                location: [0.5, 1.5],
                label   : "Drag",
                cssClass: "endpointSourceLabel",
                visible : false,
            }]
        ],
        //anchor : [  "TopCenter" , "RightMiddle" , "BottomCenter" , "LeftMiddle"  ],
        //allowLoopback:true,
        //uniqueEndpoint : false ,
        connectorOverlays  : [
            //["Arrow", {width: 10, length: 15, cssClass: "endpointSourceLabel11", location: .1}],
            //["Arrow", {width: 10, length: 15, cssClass: "endpointSourceLabel13",location: .3}],
            //["Arrow", {width: 10, length: 15, cssClass: "endpointSourceLabel15",location: .5}],
            //["Arrow", {width: 10, length: 15, cssClass: "endpointSourceLabel17",location: .7}],
            //["Arrow", {width: 10, length: 15, cssClass: "endpointSourceLabel19",location: .9}],
            //["Arrow", {width: 10, length: 15, cssClass: "endpointSourceLabel12",location: .2}],
            //["Arrow", {width: 10, length: 15, cssClass: "endpointSourceLabel14",location: .4}],
            //["Arrow", {width: 10, length: 15, cssClass: "endpointSourceLabel16",location: .6}],
            //["Arrow", {width: 10, length: 15, cssClass: "endpointSourceLabel18",location: .8}],
        ],//连接器覆盖
    };
    // 连接点样式3
    sourceEndpoint = {
        //endpoint: "Dot",
        endpoint           : ["Dot", {radius: 7}],
        paintStyle         : {
            strokeStyle: "#7AB02C",
            fillStyle  : "transparent",
            radius     : 7,
            lineWidth  : 3
        },
        isSource           : true,
        isTarget           : true,
        connector          : ["Flowchart", {stub: [40, 60], gap: 10, cornerRadius: 5, alwaysRespectStubs: true}],
        connectorStyle     : connectorPaintStyle,//基本连接线样式
        hoverPaintStyle    : endpointHoverStyle,//悬停绘图样式
        maxConnections     : -1,
        connectorOverlays  : [["Arrow", {width: 10, length: 10, location: 1}]],//连接器覆盖
        connectorHoverStyle: connectorHoverStyle,// 鼠标悬浮在连接线上的样式
        dragOptions        : {},
        overlays           : [//覆盖
            ["Label", {
                location: [0.5, 1.5],
                label   : "Drag",
                cssClass: "endpointSourceLabel",
                visible : false
            }]
        ]
    }
}

var exampleDropOptions = {
    tolerance  : "touch",
    hoverClass : "dropHover",
    activeClass: "dragActive"
};

var exampleColor = "#00f";
var exampleEndpoint = {
    endpoint      : "Rectangle",
    paintStyle    : {width: 25, height: 21, fillStyle: exampleColor},
    isSource      : true,
    reattach      : true,
    scope         : "blue",
    connectorStyle: {
        gradient   : {
            stops: [
                [0, exampleColor],
                [0.5, "#09098e"],
                [1, exampleColor]
            ]
        },
        lineWidth  : 5,
        strokeStyle: exampleColor,
        dashstyle  : "2 2"
    },
    isTarget      : true,
    beforeDrop    : function (params) {
        return confirm("Connect " + params.sourceId + " to " + params.targetId + "?");
    },
    dropOptions   : exampleDropOptions
};

var color2 = "#316b31";
var exampleEndpoint2 = {
    endpoint      : ["Dot", {radius: 11}],
    paintStyle    : {fillStyle: color2},
    isSource      : true,
    scope         : "green",
    connectorStyle: {strokeStyle: color2, lineWidth: 6},
    connector     : ["Bezier", {curviness: 63}],
    maxConnections: 3,
    isTarget      : true,
    dropOptions   : exampleDropOptions
};

var example3Color = "rgba(229,219,61,0.5)";
var exampleEndpoint3 = {
    endpoint        : ["Dot", {radius: 17}],
    anchor          : "BottomLeft",
    paintStyle      : {fillStyle: example3Color, opacity: 0.5},
    isSource        : true,
    scope           : 'yellow',
    connectorStyle  : {
        strokeStyle: example3Color,
        lineWidth  : 4
    },
    connector       : "Straight",//连接器：straight直线
    isTarget        : true,
    dropOptions     : exampleDropOptions,//拖动选项/样式
    beforeDetach    : function (conn) {//分离连接
        return confirm("Detach connection?分离连接");
    },
    onMaxConnections: function (info) {//最大连接数
        alert("不能删除连接 " + info.connection.id + " : 最大连接数已经端点上已达到 " + info.endpoint.id);
    }
};

var anchors                = [
        [1, 0.2, 1, 0],
        [0.8, 1, 0, 1],
        [0, 0.8, -1, 0],
        [0.2, 0, 0, -1]
    ],
    anchors2               = [
        [0.5, 0, 0, -1],
        [0.5, 1, 0, 1],
        [0, 0.5, -1, 0],
        [1, 0.5, 1, 0],
        [1, 0, 0, -1],
        [1, 1, 0, 1],
        [0, 0, 0, -1],
        [0, 1, 0, 1]
    ],
    maxConnectionsCallback = function (info) {
        alert("Cannot drop connection " + info.connection.id + " : maxConnections has been reached on Endpoint " + info.endpoint.id);
    };
/**
 *添加连接点
 * @param id 新建组件的id
 * @private
 */
function __jsplumb(id) {
    instance.addEndpoint(id, {anchors: "RightMiddle"}, hollowCircle);
    instance.addEndpoint(id, {anchors: "LeftMiddle"}, hollowCircle);
    instance.addEndpoint(id, {anchors: "BottomCenter"}, hollowCircle);
    instance.addEndpoint(id, {anchors: "BottomRight"}, hollowCircle);
    instance.addEndpoint(id, {anchors: "BottomLeft"}, hollowCircle);
    instance.addEndpoint(id, {anchors: 'TopCenter'}, hollowCircle);
    instance.addEndpoint(id, {anchors: 'TopRight'}, hollowCircle);
    instance.addEndpoint(id, {anchors: 'TopLeft'}, hollowCircle);
    //instance.addEndpoint(id, {anchors: [0.5,0, 0, -1, 0, -5 ]}, hollowCircle);
    //instance.endpointAnchorClass = "anchor_";
    //instance.showOverlay("myLabel");
    //instance.draggable(id);
}

//改变一条连接线的样式
var lastConnector;
/**
 * 改变线条样式
 * @param connectorType 线条的样式
 */
function changeConnectorType(connectorType) {
    lastConnector.setConnector(connectorType);
    //重写加上箭头
    lastConnector.addOverlay(["Arrow", {location: 1, width: 10, length: 13}]);
}

/*隐藏所有右击弹出层*/
function allHide() {
    $("._context").hide();
}

$(function () {
    var canvasMenu = $('#canvas_context'),
        orderMenu  = $("#_context");
    //连线样式下拉框的change事件
    $("#sel_linetype").on('change', (function () {
        var strlinetype = "";
        var strlinecolor = "";
        //设置新添加元素的节点的连线样式
        //直线的样式和样色
        if ($(this).val() == "1") {
            strlinetype = "Straight";
            strlinecolor = "red";
            instance.Defaults.Connector = ["StateMachine", {
                //stub: [0, 0],
                //gap: 0,
                proximitylimit: 500
            }];
        }
        //折线的样式和颜色
        else if ($(this).val() == "2") {
            strlinetype = "Flowchart";
            strlinecolor = "green";
            instance.Defaults.Connector = ["Flowchart", {
                stub              : [30, 30],
                gap               : 0,
                cornerRadius      : 5,
                midpoint          : 0.9,
                alwaysRespectStubs: true
            }];
        }
        //曲线的样式和颜色
        else if ($(this).val() == "3") {
            strlinetype = "Bezier";
            strlinecolor = "orange";
            instance.Defaults.Connector = ["Bezier", {
                stub              : [50, 50],
                gap               : 90,
                cornerRadius      : 5,
                curviness         : 500,
                alwaysRespectStubs: true
            }];
        }
        //设置已经存在的所有的连接点的连线样式
        var arrnode = $("#canvas").find(".window");
        for (var i = 0; i < arrnode.length; i++) {
            var arrendpoints = instance.getEndpoints($(arrnode[i]).attr("id"));
            console.log(arrendpoints);
            if (arrendpoints == undefined || arrendpoints == null) {
                return;
            }
            var oconnector = arrendpoints[0].connector;
            if (oconnector == null || oconnector == undefined) {
                return;
            }
            oconnector[0] = strlinetype;
            var oconnectstyle = arrendpoints[0].connectorStyle;
            if (oconnectstyle == null || oconnectstyle == undefined) {
                return;
            }
            oconnectstyle.strokeStyle = strlinecolor;
        }
    }));
    //让新的连接线都成直线
    //$(".line .straight").click(function () {
    //    instance.Defaults.Connector = ["Straight"];
    //    $(".line li span").removeClass("active");
    //    $(this).addClass("active");
    //});
    ////让新的连接线都成直角线
    //$(".line .flowchart").click(function () {
    //    instance.Defaults.Connector=["Flowchart", {stub: [30, 30], gap: 5, cornerRadius: 10, alwaysRespectStubs: false}];
    //    $(".line li span").removeClass("active");
    //    $(this).addClass("active");
    //});
    ////让新的连接线都成曲线
    //$(".line .bezier").click(function () {
    //    instance.Defaults.Connector = ["Bezier"];
    //    $(".line li span").removeClass("active");
    //    $(this).addClass("active");
    //});

    /*视图区域右击事件*/
    $('#canvas').contextmenu(function (e) {
        var type = $(this).attr('type');
        if (type == 'canvas') {
            allHide();
            canvasMenu.css({left: e.pageX + 'px', top: e.pageY + 'px'});
            canvasMenu.show();
        }
        /*页面刷新*/
        $('.canvas_refresh').click(function () {
            location.reload();
        })

        e.stopPropagation();
        return false;
    });

    $('body').click(function () {
        //allHide();
    })

})

